<?php

/*
 * $Id: result.php 13 2010-11-28 20:03:45Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-28 20:03:45 +0000 (Sun, 28 Nov 2010) $
 * $Revision: 13 $
 */

namespace cmFly\db\sql_constructors;

use cmFly\db;

class result implements \Countable, \Iterator, db\iStatement {

    protected $statement;
    protected $container;
    protected $current;

    public function __construct(db\iStatement $statement, $container) {
	$this->statement = $statement;
	$this->container = $container;
	$this->key = 0;
    }
    /**
     *
     * @param <type> $func
     * @param <type> $args
     * @todo remove this. Realise are native functions in php code;
     * @return <type>
     */
    public function __call($func, $args) {
	if (\method_exists($this->statement, $func)) {
	    return \call_user_func_array(Array($this->statement, $func), $args);
	}
	throw new \cmFly\system\exceptions\fatal('Method ' . \get_called_class() . '::' . $func . ' not found !');
    }

    public function rowCount() {
	return $this->statement->rowCount();
    }

    public function fetch() {
	if($this->valid()) {
	    $this->next();
	}
	else {
	    $this->rewind();
	}
	return $this->current();
    }

    public function count() {
	return $this->rowCount();
    }

    public function key() {
	return $this->key;
    }

    public function current() {
	return $this->container;
    }

    public function next() {
	$this->current=(bool)$this->statement->fetch(\PDO::FETCH_NUM);
	if($this->current) {
	    $this->key++;
	}
    }
    
    public function rewind() {
        $this->current = (bool)$this->statement->fetch(\PDO::FETCH_NUM, \PDO::FETCH_ORI_FIRST);
	$this->key=0;
	return true;
    }

    public function valid() {
	return (bool) $this->current;
    }

}